from types import *
from BeautifulSoup import BeautifulSoup
import re
import urllib
import os

from URL import URL

class ItemParser:
	'''Parser For Paper Information'''
	parseCallNum = 0

	def __init__(self, MODULE_NAME = ''):
		print 'Initializing Item Parser...'
		self.line = []
		self.data = {}
		self.lineLoaded = 0
		self.MODULE_NAME = MODULE_NAME
		self.urlManager = URL()

	def __del__(self):
		print 'Deleting ItemParser...'

	def LoadLine(self, line):
		self.line = line
		self.allItem = self.line.findAll("td")
		self.lineLoaded = line
	
	def DeloadLine(self):
		self.line = []
		selfdata = {}
		self.lineLoaded = 0

	def ParseSimpleItem(self, n):
		if not self.lineLoaded:
			print '[ERROR] in ParseSimpleItem() line not loaded'
			return
		res = {}

		reobj = re.compile('>\d+<')
		
		# print 'n: ' + str(n)
		# print 'self.allItem: ' + str(self.allItem)
	
		if type(self.allItem[n].a) is NoneType:
			res['data'] = self.allItem[n].renderContents()
		else:
			# print self.allItem[n].renderContents()
			string = re.findall(reobj, self.allItem[n].renderContents())
			s2 = string[0]
			res['data'] = s2[1:(len(s2)-1)]

		# print res
		return res





########## Function That Still Need To be Added ############
#  GetLCSSet()
###########################################################
class ItemParser2003(ItemParser):
	"Parser For Old Format"
	def __init__(self, MODULE_NAME = ''):
		print 'Initializing Old Item Parser ...'
		ItemParser.__init__(self, MODULE_NAME)

	def __def__(self):
		print 'Deleting OldItemParser...'
		ItemParser.__del__(self)


	def GetAuthorList(self, n=2):
		# print self.allItem
		reobj = re.compile('<br />[\w ;\[\]]+')
		# print self.allItem[n]
		string = re.findall(reobj, str(self.allItem[n]))
		# print self.allItem[n]
		# print n
		# print '-----------------------'
		
		reobj2 = re.compile('[> ][\w ]+[; $]')
		string2 = re.findall(reobj2, string[0])

		strangeLetterObj = re.compile('[>; ]')
		authorList = [{}] * len(string2)
		m = 0
		for string3 in string2:
			authorList[m] = re.sub(strangeLetterObj, '', string3)
			m += 1

		self.data['AuthorList'] = authorList



		# xyz

		# print self.data['AuthorList'] 
		# xyz

	def GetName(self, n=2):
		# print 'Enter GetName'
		# print self.allItem[n]

		# THIS REGULAR EXPRESSION ALWAY CAUSE ERROR. IT'S DAMN HARD TO
		# WRITE A RE THAT CAN WORK ALL THE TIME!!
		# reobj = re.compile('<br /><i>[\w -\.\d/:;?,\[\]\(\)&=>]+</i>')
		reobj = re.compile('<br /><i>.+</i>')
		string = re.findall(reobj, str(self.allItem[n]))
		# print self.allItem[n]
		# print n
		# print '----------'
		tmp = string[0]
		tmp2 = tmp[9:-4]
		strangeLetterObj = re.compile('[\./:]')
		self.data['Name'] = re.sub(strangeLetterObj, '', tmp2)
		# print string
		# print self.data['Name']
		


class ItemParser2010(ItemParser):
	'''Parser for New Format of HistCite'''
	def __init__(self, MODULE_NAME = ''):
		print 'Initializing ItemParser 2010 ...'
		ItemParser.__init__(self, MODULE_NAME)

	def __del__(self):
		print 'Deleting NewItemParser 2010...'
		ItemParser.__del__(self)

	# Simulate JavaScript in Webpage
	def opeLod(self, a, d = 'node'):
		root = './data/' + self.MODULE_NAME + '/'
		reobj = re.compile('/-/g')
		w = re.sub(reobj, '', d)
		url = root + d + '/' + a + '.html'
		return url

	# Get the URL of info pape which contain info about paper that cite this pape.
	def GetLCSURL(self):
		n = 2
		if not self.lineLoaded:
			print '[ERROR] in GetPaperFromURL() line not loaded'
			return

		# import pdb
		# if self.data['id'] == 8:
		#         pdb.set_trace()
		print n
		print self.allItem[n]


		try:

			try:
				javaScriptFunc = self.allItem[n].a['onclick']
			except:
				s = self.allItem[n].a['href']
				javaScriptFunc = s[11:]
		except:
			return -1 


		if self.data['LCS'] == 1:
			reobj = re.compile('\(.*[,]')
			result = re.findall(reobj, javaScriptFunc)
			if len(result) == 0:
				reobj = re.compile('\(.*[,)]')
				result = re.findall(reobj, javaScriptFunc)
			# print result
			val = result[0]
			para1 = val[1:(len(val)-1)]
			url = self.opeLod(para1)
			# print url
			
		else:	
			reobj = re.compile('\'[\w\d]+\'')
	 		result = re.findall(reobj, javaScriptFunc)
	 		val = result[0]
	 		para1 = val[1:(len(val)-1)]
			val = result[1]
			para2 = val[1:(len(val)-1)]
			url = self.opeLod(para2, para1)	
		return url


	def GetLCSSet(self):
		if not self.lineLoaded:
			print '[ERROR] in GetPaperFromSet() line not loaded'
			return

		if self.data['LCS'] == 0: 
			print 'No Other Paper cite this Paper'
			self.data['LCSSet'] = []
			return self.data['LCSSet']
		
		# print '----------'
		# print self.data['LCS']
		# print self.data

		url = self.GetLCSURL()
		if url == -1:
			self.data['LCSSet'] = []
			return

		# Load URL
		html = self.urlManager.LoadURL(url)

		# If URL is Node Page Info
		if self.data['LCS'] == 1:
			# self.data['CiteeSet'] = self.ParseNodeInfo(html)
			# print 'Node =1'
			self.data['LCSSet'] = self.ParseNodeInfo(html)
		else:
			# print 'Node'
			# self.data['CiteeSet'] = self.ParseCiteeInfo(html)
			self.data['LCSSet'] = self.ParseCiteeInfo(html)

	def ParseCiteeInfo(self, html):	
		print 'ParseCiteeInfo'
		soup = BeautifulSoup(html)
		body = soup.body;
		res = body.findAll('a', title=[" Article ", " Review "])
		LCSSet = [0] * len(res)
		m = 0
		for a in range(len(res)):
			LCSSet[m] = int( res[m].renderContents() )
			m = m + 1

		return LCSSet

	def ParseNodeInfo(self, html):
		soup = BeautifulSoup(html)
		titleContent = soup.title.renderContents()
		reobj = re.compile('HistCite - Record [\d]+')
		res = reobj.findall(titleContent)

		return int(res[0][18:])
		# print res

		# import pdb
		# pdb.set_trace()
	
	
	def Parse(self, line):
		print 'Enter ItemParser2010 ... '
		self.LoadLine(line)
		self.data = {} 

		# Get ID Number
		res = self.ParseSimpleItem(1)
		self.data['id'] = int( res['data'] )

		# Get LCS
		res = self.ParseSimpleItem(2)
		self.data['LCS'] = int( res['data'] )

		# Get GCS
		res = self.ParseSimpleItem(3)
		self.data['GCS'] = int( res['data'] )

		# Get LCR
		res = self.ParseSimpleItem(4)
		self.data['LCR'] = int( res['data'] )

		# Get CR
		res = self.ParseSimpleItem(5)
		self.data['CR'] = int( res['data'] )


		self.GetLCSSet()

		print self.data

		self.DeloadLine()
		return self.data

